package com.software.exception.exception.handler;

import com.software.exception.exception.enums.ExceptionCode;
import com.software.exception.exception.biz.ServiceException;
import com.software.exception.result.R;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * @program: springboot-cli-util
 * @author: Wu ZiLin
 * @create: 2023-10-26 17:00
 * @description:
 **/
@RestControllerAdvice
public class GlobalExceptionHandler {
    private static final Logger logger = LoggerFactory.getLogger(GlobalExceptionHandler.class);

    /**
     * 500 - 全局处所有未被定义的异常
     */
    @ExceptionHandler(value = Exception.class)
    public R handleError(Exception e) {
        logger.error("{}: ", ExceptionCode.INTERNAL_SERVER_ERROR.getMessage(), e);
        return R.fail(ExceptionCode.INTERNAL_SERVER_ERROR);
    }

    /**
     * 400 - 业务处理异常
     */
    @ExceptionHandler(value = ServiceException.class)
    @ResponseBody
    public R handleError(ServiceException e) {
        logger.error("{}: ", ExceptionCode.SERVICE_EXCEPTION.getMessage(), e);
        return R.fail(e.getResultCode(), e.getMessage());
    }

    /**
     * 5001 - 系统计算异常(出现无限大或无限小数)
     */
    @ExceptionHandler(ArithmeticException.class)
    public R handleError(ArithmeticException e) {
        logger.error("{}: ", ExceptionCode.SYSTEM_COMPUTATION_EXCEPTION.getMessage(), e);
        return R.fail(ExceptionCode.SYSTEM_COMPUTATION_EXCEPTION, "服务器内部错误!");
    }

    /**
     * 5002 - 内部数据格式转换异常
     */
    @ExceptionHandler(value = NumberFormatException.class)
    public R handleError(NumberFormatException e) {
        logger.error("{}: ", ExceptionCode.INTERNAL_DATA_FORMAT_ERROR.getMessage(), e);
        return R.fail(ExceptionCode.INTERNAL_DATA_FORMAT_ERROR, "服务器内部错误!");
    }

    /**
     * 5003 - 空指针异常
     */
    @ExceptionHandler(value = NullPointerException.class)
    public R handleError(NullPointerException e) {
        logger.error("{}: ", ExceptionCode.NULL_POINTER_EXCEPTION.getMessage(), e);
        return R.fail(ExceptionCode.NULL_POINTER_EXCEPTION, "服务器内部错误!");
    }
}
